package com.xinyu.utils;

import com.xinyu.vo.AttachmentFileInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class FileUploadUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUploadUtil.class);

    /**
     * 保存文件并返回新的文件路径
     * @param file 上传的文件
     * @return 新的文件路径
     * @throws IOException 如果文件保存失败
     */
    public static AttachmentFileInfo saveFile(MultipartFile file, String root_dir) throws IOException {
        String datePath = getDatePath(); // 形如 2025/02/18
        String fileName = file.getOriginalFilename();

        Path rootPath = resolveWritableRoot(root_dir);
        Path uploadDir = rootPath.resolve(datePath);
        Files.createDirectories(uploadDir);

        String newFilename = generateUUIDFilename(fileName);
        Path targetFile = uploadDir.resolve(newFilename);

        Files.write(targetFile, file.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        String relativePath = "/" + datePath.replace("\\", "/") + "/" + newFilename;

        return new AttachmentFileInfo(relativePath, fileName, file.getSize(), file.getContentType());
    }

    /**
     * 生成按系统日期分割的路径
     * 例如：2025/02/18
     * @return 格式化后的日期路径
     */
    private static String getDatePath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(new Date());
    }

    /**
     * 生成一个UUID的文件名，避免文件名重复
     * @param originalFilename 原始文件名
     * @return 新的UUID文件名
     */
    private static String generateUUIDFilename(String originalFilename) {
        String extension = "";
        if (StringUtils.isNotBlank(originalFilename) && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString() + extension;  // 使用UUID作为文件名并保持原文件扩展名
    }

    /**
     * 解析可写的根目录（对外暴露，供静态资源映射复用）。
     */
    public static Path resolveWritableRoot(String configuredRoot) throws IOException {
        Path configuredPath = null;
        if (StringUtils.isNotBlank(configuredRoot)) {
            configuredPath = Paths.get(configuredRoot).toAbsolutePath().normalize();
        }

        if (configuredPath != null) {
            try {
                Files.createDirectories(configuredPath);
                if (Files.isWritable(configuredPath)) {
                    return configuredPath;
                }
            } catch (IOException | SecurityException ex) {
                log.warn("无法写入配置的上传目录 {}，将退回到用户目录: {}", configuredPath, ex.getMessage());
            }
        }

        Path fallback = Paths.get(System.getProperty("user.home"), "HelpAttachment").toAbsolutePath().normalize();
        Files.createDirectories(fallback);
        return fallback;
    }
}
